#encoding:utf-8
from flask import request, jsonify, render_template, url_for, json
import utils
from app.ext import mongo


def register_template_filters(app):
    @app.template_filter()
    def format_long_datetime(time):
         return time.format('%Y-%M-%d %H:%M:%S')

    @app.template_filter()
    def datetimeformat(value, format='%Y-%m-%d %H:%M'):
        return value.strftime(format)

    @app.template_filter()
    def timesince(time):
        return utils.timesince(time)


    @app.template_filter()
    def url_for_other_page(page):
        '''
        得到当前页码的链接
        is_view:
                True: /views/page  , False /views?page=
        '''
        args = request.args.copy()
        args['page'] = page
        return url_for(request.endpoint, **args)

    @app.template_filter()
    def url_for_other_sort(sort):
        args = request.view_args.copy()
        args['sort'] = sort
        return url_for(request.endpoint, **args)

    @app.template_filter()
    def url_for_page():
        args = request.view_args.copy()
        return url_for(request.endpoint,**args)

    @app.template_filter()
    def format_date(tm, type_int):

        return utils.format_date(tm, type_int)


    @app.template_filter()
    def render_gender(gender):
        if not gender or gender == "":
            return u"保密"
        else:
            return u'男' if gender=='male' else u'女'


def error_handers(app):

    @app.errorhandler(401)
    def unauthorized(error):
        if request.is_xhr:
            return jsonify(success=False, error=u"请先登录", login=True, next=request.url)
        return render_template('errors/401.html',error=error)

    @app.errorhandler(403)
    def forbidden(error):
        if request.is_xhr:
            return jsonify(success=False,error=error)
        return render_template('errors/403.html',error=error)

    @app.errorhandler(404)
    def page_not_found(error):
        if request.is_xhr:
            return json.dumps(success=False,error='页面未找到')
        return render_template('errors/404.html',error=error)

    @app.errorhandler(413)
    def request_entity_too_large(error):
        if request.is_xhr:
            return jsonify(success=False,error='Request Entity too Large')
        return render_template('errors/404.html',error=error)

    @app.errorhandler(500)
    def server_error(error):
        if request.is_xhr:
            return jsonify(error=u'服务器内部错误',success=False)
        return render_template('errors/500.html',error=error)
